<template>
  <div class="cart">
    <div class="page-header">
      <h2>购物车</h2>
      <button 
        v-if="cartItems.length > 0" 
        @click="clearCart" 
        class="clear-btn"
      >
        清空购物车
      </button>
    </div>
    
    <div v-if="loading" class="loading">加载中...</div>
    <div v-else-if="error" class="error">{{ error }}</div>
    <div v-else-if="cartItems.length === 0" class="empty">
      <p>购物车是空的</p>
      <router-link to="/customer/products" class="continue-shopping">
        继续购物
      </router-link>
    </div>
    
    <div v-else class="cart-content">
      <div class="cart-items">
        <div v-for="item in cartItems" :key="item.id" class="cart-item">
          <img :src="item.image" :alt="item.name" class="item-image" />
          <div class="item-info">
            <h3>{{ item.name }}</h3>
            <p class="item-price">¥{{ item.price.toFixed(2) }}</p>
          </div>
          <div class="item-quantity">
            <button 
              @click="decreaseQuantity(item)" 
              class="quantity-btn"
              :disabled="item.quantity <= 1"
            >
              -
            </button>
            <span class="quantity">{{ item.quantity }}</span>
            <button 
              @click="increaseQuantity(item)" 
              class="quantity-btn"
            >
              +
            </button>
          </div>
          <div class="item-total">
            ¥{{ (item.price * item.quantity).toFixed(2) }}
          </div>
          <button @click="removeItem(item.id)" class="remove-btn">
            删除
          </button>
        </div>
      </div>
      
      <div class="cart-summary">
        <div class="summary-row">
          <span>商品总数：</span>
          <span>{{ totalItems }} 件</span>
        </div>
        <div class="summary-row total">
          <span>总计：</span>
          <span class="total-price">¥{{ totalPrice.toFixed(2) }}</span>
        </div>
        <button @click="checkout" class="checkout-btn" :disabled="loading">
          {{ loading ? '处理中...' : '立即结算' }}
        </button>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref } from 'vue'
import { useRouter } from 'vue-router'
import { storeToRefs } from 'pinia'
import { useCartStore } from '../../stores/cart'
import { useOrderStore } from '../../stores/order'

const router = useRouter()
const cartStore = useCartStore()
const orderStore = useOrderStore()

const { cartItems, totalItems, totalPrice, loading, error } = storeToRefs(cartStore)

const increaseQuantity = async (item) => {
  try {
    await cartStore.updateQuantity(item.id, item.quantity + 1)
  } catch (err) {
    alert('更新数量失败：' + err.message)
  }
}

const decreaseQuantity = async (item) => {
  if (item.quantity <= 1) return
  try {
    await cartStore.updateQuantity(item.id, item.quantity - 1)
  } catch (err) {
    alert('更新数量失败：' + err.message)
  }
}

const removeItem = async (itemId) => {
  if (confirm('确定要删除这个商品吗？')) {
    try {
      await cartStore.removeFromCart(itemId)
    } catch (err) {
      alert('删除商品失败：' + err.message)
    }
  }
}

const clearCart = async () => {
  if (confirm('确定要清空购物车吗？')) {
    try {
      await cartStore.clearCart()
    } catch (err) {
      alert('清空购物车失败：' + err.message)
    }
  }
}

const checkout = async () => {
  if (cartItems.value.length === 0) {
    alert('购物车是空的！')
    return
  }
  
  if (!confirm('确定要结算吗？')) return
  
  try {
    // 创建订单
    const orderData = {
      items: cartItems.value.map(item => ({
        productId: item.productId,
        name: item.name,
        price: item.price,
        quantity: item.quantity,
        image: item.image
      })),
      totalPrice: totalPrice.value,
      totalItems: totalItems.value
    }
    
    const order = await orderStore.createOrder(orderData)
    
    // 清空购物车
    await cartStore.clearCart()
    
    alert('订单创建成功！')
    router.push('/customer/orders')
  } catch (err) {
    alert('结算失败：' + err.message)
  }
}
</script>

<style scoped>
.cart {
  background: white;
  border-radius: 8px;
  padding: 20px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.page-header h2 {
  margin: 0;
  color: #333;
}

.clear-btn {
  padding: 8px 16px;
  background: #ff4757;
  color: white;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  font-size: 14px;
  transition: background-color 0.3s;
}

.clear-btn:hover {
  background: #ff3742;
}

.loading, .error, .empty {
  text-align: center;
  padding: 40px;
  font-size: 16px;
}

.error {
  color: #e74c3c;
}

.empty {
  color: #666;
}

.continue-shopping {
  display: inline-block;
  margin-top: 15px;
  padding: 10px 20px;
  background: #667eea;
  color: white;
  text-decoration: none;
  border-radius: 5px;
  transition: background-color 0.3s;
}

.continue-shopping:hover {
  background: #5a6fd8;
}

.cart-content {
  display: flex;
  gap: 30px;
}

.cart-items {
  flex: 1;
}

.cart-item {
  display: flex;
  align-items: center;
  gap: 15px;
  padding: 15px;
  border: 1px solid #e0e0e0;
  border-radius: 8px;
  margin-bottom: 15px;
  background: #fafafa;
}

.item-image {
  width: 80px;
  height: 80px;
  object-fit: cover;
  border-radius: 4px;
}

.item-info {
  flex: 1;
}

.item-info h3 {
  margin: 0 0 5px 0;
  color: #333;
  font-size: 16px;
}

.item-price {
  color: #ff4757;
  font-weight: bold;
  margin: 0;
}

.item-quantity {
  display: flex;
  align-items: center;
  gap: 10px;
}

.quantity-btn {
  width: 30px;
  height: 30px;
  border: 1px solid #ddd;
  background: white;
  border-radius: 4px;
  cursor: pointer;
  font-size: 16px;
  font-weight: bold;
  transition: all 0.2s;
}

.quantity-btn:hover:not(:disabled) {
  background: #f8f9ff;
  border-color: #667eea;
  color: #667eea;
}

.quantity-btn:disabled {
  opacity: 0.5;
  cursor: not-allowed;
}

.quantity {
  font-weight: bold;
  color: #333;
  min-width: 30px;
  text-align: center;
}

.item-total {
  font-size: 16px;
  font-weight: bold;
  color: #ff4757;
  min-width: 80px;
  text-align: right;
}

.remove-btn {
  padding: 6px 12px;
  background: #ff4757;
  color: white;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  font-size: 12px;
  transition: background-color 0.3s;
}

.remove-btn:hover {
  background: #ff3742;
}

.cart-summary {
  width: 300px;
  background: #f8f9ff;
  padding: 20px;
  border-radius: 8px;
  height: fit-content;
}

.summary-row {
  display: flex;
  justify-content: space-between;
  margin-bottom: 10px;
  font-size: 14px;
}

.summary-row.total {
  font-size: 18px;
  font-weight: bold;
  color: #333;
  padding-top: 10px;
  border-top: 2px solid #667eea;
}

.total-price {
  color: #ff4757;
}

.checkout-btn {
  width: 100%;
  padding: 12px;
  background: #667eea;
  color: white;
  border: none;
  border-radius: 5px;
  font-size: 16px;
  font-weight: bold;
  cursor: pointer;
  margin-top: 15px;
  transition: background-color 0.3s;
}

.checkout-btn:hover:not(:disabled) {
  background: #5a6fd8;
}

.checkout-btn:disabled {
  opacity: 0.7;
  cursor: not-allowed;
}

@media (max-width: 768px) {
  .cart-content {
    flex-direction: column;
  }
  
  .cart-summary {
    width: 100%;
  }
  
  .cart-item {
    flex-wrap: wrap;
    gap: 10px;
  }
  
  .item-info {
    order: 2;
    flex-basis: 100%;
  }
  
  .item-quantity {
    order: 3;
  }
  
  .item-total {
    order: 4;
  }
  
  .remove-btn {
    order: 5;
  }
}
</style>